package com.site.springboot.core.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.site.springboot.core.dao.NewsCommentMapper;
import com.site.springboot.core.pojo.entity.NewsComment;
import com.site.springboot.core.service.CommentService;
import com.site.springboot.core.util.PageQueryUtil;
import com.site.springboot.core.util.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;

@Service
public class CommentServiceImpl implements CommentService {
    @Autowired
    private NewsCommentMapper newsCommentMapper;

    @Override
    public Boolean addComment(NewsComment newsComment) {
        return newsCommentMapper.insert(newsComment) > 0;
    }

    @Override
    public PageResult getCommentsPage(PageQueryUtil pageUtil) {
        Page<NewsComment> page = new Page<>(pageUtil.getPage(), pageUtil.getLimit());
        QueryWrapper<NewsComment> queryWrapper = new QueryWrapper<>();
        Page<NewsComment> newsCommentPage = newsCommentMapper.selectPage(page, queryWrapper.eq("is_deleted", 0).orderByDesc("comment_id"));

        int total = newsCommentMapper.selectCount(queryWrapper.eq("is_deleted", 0)).intValue();
        PageResult pageResult = new PageResult(newsCommentPage.getRecords(), total, pageUtil.getLimit(), pageUtil.getPage());
        return pageResult;
    }

    @Override
    public Boolean checkDone(Integer[] ids) {
        UpdateWrapper<NewsComment> updateWrapper = new UpdateWrapper<>();
        updateWrapper.set("comment_status", 1).in("comment_id", ids) // 使用 in 条件，传入需要更新的评论ID集合
                .eq("comment_status", 0); // 评论状态为0的记录

        // 调用 newsCommentMapper 更新记录
        return newsCommentMapper.update(null, updateWrapper) > 0;
    }

    @Override
    public Boolean deleteBatch(Integer[] ids) {
        return newsCommentMapper.deleteBatchIds(Arrays.asList(ids)) > 0;
    }

    /**
     * 实现获取前五条评论
     * @return
     */
    @Override
    public List<NewsComment> getAllCommentOrderBy() {
        return newsCommentMapper.selectList(new QueryWrapper<NewsComment>().eq("is_deleted", 0).orderByDesc("comment_id").last("limit 5"));
    }
}
